package com.uday.kraterchat.chatclient.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	import com.uday.frmwrk.data.BaseResponseItem;
	import com.uday.kraterchat.chatclient.business.UserServiceDelegate;
	import com.uday.kraterchat.chatclient.control.KeepAliveEvent;
	import com.uday.kraterchat.chatclient.control.LoginUserEvent;
	import com.uday.kraterchat.chatclient.control.SubscribeMsgEvent;
	import com.uday.kraterchat.chatclient.data.LoginInfoItem;
	import com.uday.kraterchat.chatclient.data.UserInfoDetItem;
	import com.uday.kraterchat.chatclient.model.ChatClientModel;
	import com.uday.kraterchat.chatclient.view.Login;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.messaging.events.MessageEvent;
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	
	public class LoginUserCommand implements ICommand, IResponder
	{
		private var objChatClientModel:ChatClientModel = ChatClientModel.getInstance();
		
		public function LoginUserCommand()
		{
		}

		public function execute(event:CairngormEvent):void
		{
			var objLoginUserDel:UserServiceDelegate = new UserServiceDelegate(this);
			objLoginUserDel.loginUser((event as LoginUserEvent).objDataItem as LoginInfoItem);
		}
		
		public function result(event:Object):void
		{
			var objBaseResponseItem:BaseResponseItem = (event as ResultEvent).result as BaseResponseItem;
			if(objBaseResponseItem.lstErrorList.length == 0){
				var lstResp:ArrayCollection = objBaseResponseItem.lstDataItems;
				objChatClientModel.objCurrUser = lstResp.getItemAt(0) as UserInfoDetItem;
				objChatClientModel.lstFriends = lstResp.getItemAt(1) as ArrayCollection;
				objChatClientModel.mainAppState = KraterChatAir.STATE_FRIENDS_LIST;
				CairngormEventDispatcher.getInstance().dispatchEvent(new SubscribeMsgEvent(objChatClientModel.objCurrUser.strMsgQueueID));
				
				startAliveSignals();
			} else{
				Alert.show(objBaseResponseItem.lstErrorList.getItemAt(0).toString());
				objChatClientModel.loginPageState = Login.STATE_WRONG_VALUES;
			}
		}
		
		private function startAliveSignals():void{
			var objTimer:Timer = objChatClientModel.objKeepAliveTimer;
			objTimer.addEventListener(TimerEvent.TIMER,function(event:TimerEvent):void{
				CairngormEventDispatcher.getInstance().dispatchEvent(new KeepAliveEvent(objChatClientModel.objCurrUser));
			});
			objTimer.start();
			
		}
		
		public function fault(info:Object):void
		{
			Alert.show("User Login Query Failed");
		}
		
		private function friendListhandler(event:MessageEvent):void{
			objChatClientModel.lstFriends = event.message.body as ArrayCollection;
		}
		
	}
}